package com.lagou.tomcat.server;

import com.lagou.tomcat.http.HttpStatusEnum;
import com.lagou.tomcat.http.Request;
import com.lagou.tomcat.http.Response;
import com.lagou.tomcat.servlet.Servlet;
import com.lagou.tomcat.servlet.ServletContext;
import com.lagou.tomcat.utils.ResourcesUtil;
import com.lagou.tomcat.utils.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;

/**
 * 创建人: yyn
 * 创建时间:2021/9/4 22:25
 */
public class Tomcat {

    private int port;

    private ServerSocket serverSocket;

    private ServletContext servletContext;

    public Tomcat(int port) {
        this.port = port;
        try {
            this.init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void init() throws IOException {
        serverSocket = new ServerSocket(port);
        servletContext = new ServletContext();
    }

    public void start() throws IOException, InterruptedException {
        System.out.println("tomcat以启动");
        while (true) {
            Socket socket = serverSocket.accept();
            Request request = Request.create(socket.getInputStream());
            if (ResourcesUtil.isStatic(request.getUri())) {
                // 获取静态资源
                String absolutePath = StaticResourceUtil.getAbsolutePath(request.getUri());
                File file = new File(absolutePath);
                FileInputStream inputStream = new FileInputStream(file);
                Response response = Response.create(socket.getOutputStream());
                response.print(HttpStatusEnum.SUCCESS, inputStream);
            } else {
                // 获取动态资源 servlet
                Servlet servlet = servletContext.getServlet(request.getUri());
                if (servlet == null) {
                    // 返回404
                } else {
                    servlet.doService(request, Response.create(socket.getOutputStream()));
                }
            }
            socket.close();
        }

    }
}
